#include "UsrAI.h"
#include "AI.h"
#include "config.h"
#include <set>
#include <iostream>
#include <unordered_map>
#include <map>
#include <vector>
#include <string>
#include <cmath>
using namespace std;

// 前置声明
int getWorkerCount(int resourceType);
int getTargetCount(int resourceType);

tagGame tagUsrGame;
ins UsrIns;
int begin_x = 0, begin_y = 0;
int center_x = 0, center_y = 0;
bool home_flag = false;
int home_count = 0;
bool dock_built = false;
int dock_sn = -1;
int fishing_boat_count = 0;
char game_map[128][128] = {0};
tagInfo info;
// 防止同时建造相同建筑的计数器
static int dock_build_attempts = 0;
// 游戏阶段控制
static int stage = 1;
// Stage1人口控制配置
struct Stage1PopulationControl {
    int max_population_stage1 = 24;  // Stage1最大人口限制
    int food_reserve_threshold = 400;  // 开始积累食物的阈值
    bool saving_for_upgrade = false;   // 是否正在为升级积累食物
} stage1PopControl;
// Stage2：海洋探索相关
struct ExplorationData {
    set<pair<int, int>> explored_positions;  // 已探索的海洋位置
    vector<pair<int, int>> enemy_land_positions;  // 发现的敌方大陆位置
    bool enemy_mainland_found = false;
    int exploration_radius = 1;  // 当前探索半径
} exploration;
// Stage2新增数据结构和变量
struct PopulationManager {
    int maxPopulation = 50;
    int optimalVillagers = 18;  // 保留核心村民数量
    int targetMilitary = 25;    // 目标军事单位数量

    bool needPopulationOptimization() {
        int currentTotal = info.farmers.size() + info.armies.size();
        return (currentTotal >= maxPopulation - 5);
    }
} popManager;

struct LandArmyPlan {
    int clubmanTarget = 8;       // 棍棒兵目标数量
    int slingerTarget = 6;       // 投石兵目标数量
    int archerTarget = 6;        // 弓箭手目标数量
    int scoutTarget = 2;         // 侦察骑兵目标数量

    int currentClubman = 0;
    int currentSlinger = 0;
    int currentArcher = 0;
    int currentScout = 0;

    void updateCounts() {
        currentClubman = currentSlinger = currentArcher = currentScout = 0;
        for (const tagArmy& army : info.armies) {
            switch(army.Sort) {
                case AT_CLUBMAN: currentClubman++; break;
                case AT_SWORDSMAN: currentClubman++; break;  // 战斧兵也算
                case AT_SLINGER: currentSlinger++; break;
                case AT_BOWMAN: currentArcher++; break;
                case AT_SCOUT: currentScout++; break;
            }
        }
    }
} landArmy;

struct MilitaryBuildings {
    bool hasArcheryRange = false;
    bool hasStable = false;
    int barracksCount = 0;

    void updateStatus() {
        hasArcheryRange = hasStable = false;
        barracksCount = 0;

        for (const tagBuilding& b : info.buildings) {
            if (b.Percent == 100) {  // 只统计完成的建筑
                switch(b.Type) {
                    case BUILDING_RANGE: hasArcheryRange = true; break;
                    case BUILDING_STABLE: hasStable = true; break;
                    case BUILDING_ARMYCAMP: barracksCount++; break;
                }
            }
        }
    }
} militaryBuildings;

struct UpgradeStatus {
    bool clubmanUpgraded = false;      // 棍棒兵升级完成
    bool toolsUpgraded = false;        // 工具利用升级
    bool infantryArmorUpgraded = false; // 步兵护甲升级
    bool archerArmorUpgraded = false;   // 弓兵护甲升级

    void checkUpgrades() {
        // 通过检查是否有战斧兵来判断棍棒兵升级状态
        clubmanUpgraded = false;
        for (const tagArmy& army : info.armies) {
            if (army.Sort == AT_SWORDSMAN) {
                clubmanUpgraded = true;
                break;
            }
        }
        // 其他升级状态需要通过技术研究状态检查，这里简化处理
    }
} upgradeStatus;

// Stage2新增：战船管理
struct NavalForce {
    int target_warships = 6;  // 目标战船数量
    int current_warships = 0;
    vector<int> warship_sns;  // 战船SN列表
    bool naval_supremacy = false;  // 是否掌控制海权
} naval;

// 资源采集目标配置（根据阶段调整）
struct ResourceTargets {
    int target_woodcutters = 8;
    int target_hunters = 4;
    int target_miners = 3;
    int target_fishers = 5;

    int current_woodcutters = 0;
    int current_hunters = 0;
    int current_miners = 0;
    int current_fishers = 0;

    // Stage2调整资源分配
    void adjustForStage2() {
        target_woodcutters = 12;  // 增加木材需求（造船）
        target_hunters = 2;       // 减少打猎
        target_miners = 2;        // 减少采石
        target_fishers = 6;       // 增加捕鱼
    }

    int getMostNeededJob() {
        double wood_ratio = (double)current_woodcutters / target_woodcutters;
        double hunt_ratio = (double)current_hunters / target_hunters;
        double mine_ratio = (double)current_miners / target_miners;

        if (wood_ratio <= hunt_ratio && wood_ratio <= mine_ratio) {
            return RESOURCE_TREE;
        } else if (hunt_ratio <= mine_ratio) {
            return RESOURCE_GAZELLE;
        } else {
            return RESOURCE_STONE;
        }
    }

    bool needMoreWorkers(int resourceType) {
        switch(resourceType) {
            case RESOURCE_TREE: return current_woodcutters < target_woodcutters;
            case RESOURCE_GAZELLE: return current_hunters < target_hunters;
            case RESOURCE_STONE: return current_miners < target_miners;
            default: return false;
        }
    }
} resourceTargets;
// 建造状态跟踪，避免重复建造
struct BuildingTracker {
    bool barracks_building = false;
    bool granary_building = false;
    bool storage_building = false;
    bool dock_building = false;  // 新增：船坞建造跟踪

    void updateStatus() {
        barracks_building = false;
        granary_building = false;
        storage_building = false;
        dock_building = false;  // 新增

        // 检查是否有建筑正在建造中
        for (const tagBuilding& b : info.buildings) {
            if (b.Percent < 100) {  // 建造中
                switch(b.Type) {
                    case BUILDING_ARMYCAMP: barracks_building = true; break;
                    case BUILDING_GRANARY: granary_building = true; break;
                    case BUILDING_STOCK: storage_building = true; break;
                    case BUILDING_DOCK: dock_building = true; break;  // 新增
                }
            }
        }
    }
} buildingTracker;
// 资源分配状态跟踪
unordered_map<int, bool> resourceLocks;
unordered_map<int, int> workerAssignments;
// 升级状态跟踪
bool upgrading_in_progress = false;
// 原有函数保持不变
bool isAreaFree(int x, int y, int size = 2) {
    for (int i = x; i < x + size && i < 128; i++) {
        for (int j = y; j < y + size && j < 128; j++) {
            if (game_map[i][j] >= 3 && game_map[i][j] <= 5) {
                return false;
            }
        }
    }
    return true;
}
// 原有的辅助函数保持不变
int getWorkerCount(int resourceType) {
    switch(resourceType) {
        case RESOURCE_TREE: return resourceTargets.current_woodcutters;
        case RESOURCE_GAZELLE: return resourceTargets.current_hunters;
        case RESOURCE_STONE: return resourceTargets.current_miners;
        default: return 0;
    }
}

int getTargetCount(int resourceType) {
    switch(resourceType) {
        case RESOURCE_TREE: return resourceTargets.target_woodcutters;
        case RESOURCE_GAZELLE: return resourceTargets.target_hunters;
        case RESOURCE_STONE: return resourceTargets.target_miners;
        default: return 0;
    }
}

int getDistance(int x1, int y1, int x2, int y2) {
    return abs(x1 - x2) + abs(y1 - y2);
}

double getExactDistanceSquared(double x1, double y1, double x2, double y2) {
    return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
int find_block(int& x, int& y, bool is_dock = false) {
    for (int i = begin_x; i < 128; i++) {
        int start_j = (i == begin_x) ? begin_y : 0;
        for (int j = start_j; j < 128; j++) {
            if (i + 1 >= 128 || j + 1 >= 128) continue;

            if (is_dock) {
                if (game_map[i][j] != 2 || game_map[i+1][j] != 2 ||
                    game_map[i][j+1] != 2 || game_map[i+1][j+1] != 2) continue;
                bool has_land = false;
                for (int di = -1; di <= 2; di++) {
                    for (int dj = -1; dj <= 2; dj++) {
                        if ((di == -1 || di == 2 || dj == -1 || dj == 2) &&
                            i+di >= 0 && i+di < 128 && j+dj >= 0 && j+dj < 128) {
                            if (game_map[i+di][j+dj] == 1) {
                                has_land = true;
                                break;
                            }
                        }
                    }
                    if (has_land) break;
                }
                if (!has_land) continue;
            } else {
                if (game_map[i][j] != 1 || game_map[i+1][j] != 1 ||
                    game_map[i][j+1] != 1 || game_map[i+1][j+1] != 1) continue;
                int height = (*info.theMap)[i][j].height;
                if ((*info.theMap)[i+1][j].height != height ||
                    (*info.theMap)[i][j+1].height != height ||
                    (*info.theMap)[i+1][j+1].height != height) continue;
            }

            if (isAreaFree(i, j, 2)) {
                x = i;
                y = j;
                begin_x = i;
                begin_y = (j + 1) % 128;
                if (begin_y == 0) begin_x++;
                return 1;
            }
        }
    }
    begin_x = 0;
    begin_y = 0;
    return 0;
}
// 添加海洋探索管理结构
struct OceanExplorationManager {
    set<pair<int, int>> exploredOceanTiles;  // 已探索的海洋格子
    vector<pair<int, int>> explorationTargets;  // 探索目标点
    int currentExplorationRadius = 15;  // 当前探索半径

    // 为128*128地图生成系统化的探索目标点
    void generateExplorationTargets() {
        explorationTargets.clear();

        // 在地图上设置探索网格点，覆盖整个海洋区域
        for (int x = 20; x <= 108; x += 25) {  // 每25格设置一个探索点
            for (int y = 20; y <= 108; y += 25) {
                explorationTargets.push_back({x, y});
            }
        }

        // 添加边界探索点
        vector<pair<int, int>> boundaryPoints = {
            {10, 64}, {118, 64},   // 左右边界中点
            {64, 10}, {64, 118},   // 上下边界中点
            {20, 20}, {108, 20},   // 四个角落附近
            {20, 108}, {108, 108}
        };

        for (auto& point : boundaryPoints) {
            explorationTargets.push_back(point);
        }

       // DebugText("生成了" + to_string(explorationTargets.size()) + "个海洋探索目标点");
}
    // 获取最近的未探索目标点
    pair<int, int> getNearestUnexploredTarget(int ship_x, int ship_y) {
        pair<int, int> bestTarget = {-1, -1};
        double minDist = 1e9;

        for (auto& target : explorationTargets) {
            // 检查是否已经被探索过（在附近20格范围内）
            bool isExplored = false;
            for (auto& explored : exploredOceanTiles) {
                if (getDistance(target.first, target.second, explored.first, explored.second) < 20) {
                    isExplored = true;
                    break;
                }
            }

            if (!isExplored) {
                double dist = getExactDistanceSquared(ship_x, ship_y, target.first, target.second);
                if (dist < minDist) {
                    minDist = dist;
                    bestTarget = target;
                }
            }
        }

        return bestTarget;
    }

    // 标记区域为已探索
    void markAsExplored(int x, int y) {
        exploredOceanTiles.insert({x, y});
    }
} oceanExplorer;

int findNearestFish(int x, int y) {
    int nearest_sn = -1;
    double min_dist = 1e9;

    for (const tagResource& res : info.resources) {
        if (res.Type == RESOURCE_FISH && res.Cnt > 0) {
            double dist = getExactDistanceSquared(x, y, res.DR, res.UR);
            if (dist < min_dist) {
                min_dist = dist;
                nearest_sn = res.SN;
            }
        }
    }
    return nearest_sn;
}

// 改进的渔船探索函数（替换原有的assignFishingJobs部分探索逻辑）
void UsrAI::enhancedFishingExploration() {
    // 如果还没有生成探索目标，先生成
    if (oceanExplorer.explorationTargets.empty()) {
        oceanExplorer.generateExplorationTargets();
    }

    for (const tagFarmer& farmer : info.farmers) {
        if (farmer.FarmerSort == 2 && farmer.NowState == HUMAN_STATE_IDLE) {
            int fish_sn = findNearestFish(farmer.BlockDR, farmer.BlockUR);
            if (fish_sn != -1) {
                HumanAction(farmer.SN, fish_sn);
                DebugText("分配渔船" + to_string(farmer.SN) + "前往渔场" + to_string(fish_sn));
            } else {
                // 系统化海洋探索
                auto target = oceanExplorer.getNearestUnexploredTarget(farmer.BlockDR, farmer.BlockUR);

                if (target.first != -1) {
                    // 向目标点探索
                    double target_x = target.first * BLOCKSIDELENGTH;
                    double target_y = target.second * BLOCKSIDELENGTH;
                    HumanMove(farmer.SN, target_x, target_y);
                    DebugText("渔船" + to_string(farmer.SN) + "系统化探索海洋目标(" +
                             to_string(target.first) + "," + to_string(target.second) + ")");
                } else {
                    // 所有目标点都探索完了，进行随机远距离探索
                    int explore_x = 20 + rand() % 88;  // 20-108范围
                    int explore_y = 20 + rand() % 88;
                    HumanMove(farmer.SN, explore_x * BLOCKSIDELENGTH, explore_y * BLOCKSIDELENGTH);
                    DebugText("渔船" + to_string(farmer.SN) + "随机深海探索(" +
                             to_string(explore_x) + "," + to_string(explore_y) + ")");
                }

                // 标记当前位置附近为已探索
                oceanExplorer.markAsExplored(farmer.BlockDR, farmer.BlockUR);
            }
        }
    }
}

// 新增：运输船探索功能（Stage1也可以用于提前侦察）
void UsrAI::exploreWithTransportShips() {
    for (const tagFarmer& farmer : info.farmers) {
        if (farmer.FarmerSort == 1 && farmer.NowState == HUMAN_STATE_IDLE && farmer.Resource == 0) {
            // 运输船为空且空闲时进行探索
            auto target = oceanExplorer.getNearestUnexploredTarget(farmer.BlockDR, farmer.BlockUR);

            if (target.first != -1) {
                double target_x = target.first * BLOCKSIDELENGTH;
                double target_y = target.second * BLOCKSIDELENGTH;
                HumanMove(farmer.SN, target_x, target_y);
                DebugText("运输船" + to_string(farmer.SN) + "探索海洋(" +
                         to_string(target.first) + "," + to_string(target.second) + ")");

                // 标记为已探索
                oceanExplorer.markAsExplored(farmer.BlockDR, farmer.BlockUR);
            }
        }
    }
}
// Stage2新增函数

// 人口优化：让多余村民自毁
void UsrAI::optimizePopulation() {
    if (!popManager.needPopulationOptimization()) return;

    int currentVillagers = 0;
    for (const tagFarmer& farmer : info.farmers) {
        if (farmer.FarmerSort == 0) currentVillagers++;
    }

    if (currentVillagers <= popManager.optimalVillagers) return;

    // 找到闲置村民让其自毁
    for (const tagFarmer& farmer : info.farmers) {
        if (farmer.FarmerSort == 0 && farmer.NowState == HUMAN_STATE_IDLE) {
            HumanAction(farmer.SN, farmer.SN);  // 自毁指令
            DebugText("村民" + to_string(farmer.SN) + "自毁腾出人口空间");
            return;  // 一次只处理一个
        }
    }
}
// 建造军事建筑
void UsrAI::buildMilitaryInfrastructure() {
    // 优先建造第二个兵营
    if (militaryBuildings.barracksCount < 2 && info.Wood >= BUILD_ARMYCAMP_WOOD) {
        for (const tagFarmer& farmer : info.farmers) {
            if (farmer.FarmerSort == 0 && farmer.NowState == HUMAN_STATE_IDLE) {
                int barracks_x, barracks_y;
                if (find_block(barracks_x, barracks_y)) {
                    HumanBuild(farmer.SN, BUILDING_ARMYCAMP, barracks_x, barracks_y);
                    DebugText("建造第二个兵营");
                    return;
                }
            }
        }
    }

    // 建造靶场
    if (!militaryBuildings.hasArcheryRange && militaryBuildings.barracksCount >= 1 &&
        info.Wood >= BUILD_RANGE_WOOD) {
        for (const tagFarmer& farmer : info.farmers) {
            if (farmer.FarmerSort == 0 && farmer.NowState == HUMAN_STATE_IDLE) {
                int range_x, range_y;
                if (find_block(range_x, range_y)) {
                    HumanBuild(farmer.SN, BUILDING_RANGE, range_x, range_y);
                    DebugText("建造靶场");
                    return;
                }
            }
        }
    }

    // 建造马厩
    if (!militaryBuildings.hasStable && militaryBuildings.hasArcheryRange &&
        info.Wood >= BUILD_STABLE_WOOD) {
        for (const tagFarmer& farmer : info.farmers) {
            if (farmer.FarmerSort == 0 && farmer.NowState == HUMAN_STATE_IDLE) {
                int stable_x, stable_y;
                if (find_block(stable_x, stable_y)) {
                    HumanBuild(farmer.SN, BUILDING_STABLE, stable_x, stable_y);
                    DebugText("建造马厩");
                    return;
                }
            }
        }
    }
}

// 生产陆军单位
void UsrAI::produceLandArmy() {
    // 生产优先级：棍棒兵 -> 投石兵 -> 弓箭手 -> 骑兵

    // 1. 生产棍棒兵（优先级最高）
    if (landArmy.currentClubman < landArmy.clubmanTarget &&
        info.Meat >= BUILDING_ARMYCAMP_CREATE_CLUBMAN_FOOD) {
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_ARMYCAMP && b.Project == 0 && b.Percent == 100) {
                BuildingAction(b.SN, BUILDING_ARMYCAMP_CREATE_CLUBMAN);
                DebugText("兵营生产棍棒兵(" + to_string(landArmy.currentClubman) + "/" +
                         to_string(landArmy.clubmanTarget) + ")");
                return;
            }
        }
    }

    // 2. 生产投石兵
    if (landArmy.currentSlinger < landArmy.slingerTarget &&
        info.Meat >= BUILDING_ARMYCAMP_CREATE_SLINGER_FOOD &&
        info.Stone >= BUILDING_ARMYCAMP_CREATE_SLINGER_STONE) {
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_ARMYCAMP && b.Project == 0 && b.Percent == 100) {
                BuildingAction(b.SN, BUILDING_ARMYCAMP_CREATE_SLINGER);
                DebugText("兵营生产投石兵(" + to_string(landArmy.currentSlinger) + "/" +
                         to_string(landArmy.slingerTarget) + ")");
                return;
            }
        }
    }

    // 3. 生产弓箭手
    if (landArmy.currentArcher < landArmy.archerTarget && militaryBuildings.hasArcheryRange &&
        info.Meat >= BUILDING_RANGE_CREATE_BOWMAN_FOOD &&
        info.Wood >= BUILDING_RANGE_CREATE_BOWMAN_WOOD) {
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_RANGE && b.Project == 0 && b.Percent == 100) {
                BuildingAction(b.SN, BUILDING_RANGE_CREATE_BOWMAN);
                DebugText("靶场生产弓箭手(" + to_string(landArmy.currentArcher) + "/" +
                         to_string(landArmy.archerTarget) + ")");
                return;
            }
        }
    }

    // 4. 生产侦察骑兵
    if (landArmy.currentScout < landArmy.scoutTarget && militaryBuildings.hasStable &&
        info.Meat >= BUILDING_STABLE_CREATE_SCOUT_FOOD) {
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_STABLE && b.Project == 0 && b.Percent == 100) {
                BuildingAction(b.SN, BUILDING_STABLE_CREATE_SCOUT);
                DebugText("马厩生产侦察骑兵(" + to_string(landArmy.currentScout) + "/" +
                         to_string(landArmy.scoutTarget) + ")");
                return;
            }
        }
    }
}

// 军事升级管理
void UsrAI::manageMilitaryUpgrades() {
    // 1. 棍棒兵升级为战斧兵（当棍棒兵>=6时）
    if (!upgradeStatus.clubmanUpgraded && landArmy.currentClubman >= 6 &&
        info.Meat >= BUILDING_ARMYCAMP_UPGRADE_CLUBMAN_FOOD) {
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_ARMYCAMP && b.Project == 0 && b.Percent == 100) {
                BuildingAction(b.SN, BUILDING_ARMYCAMP_UPGRADE_CLUBMAN);
                DebugText("兵营升级棍棒兵为战斧兵");
                return;
            }
        }
    }

    // 2. 步兵护甲升级（当近战单位>=8时）
    if (!upgradeStatus.infantryArmorUpgraded &&
        (landArmy.currentClubman >= 8) &&
        info.Meat >= BUILDING_STOCK_UPGRADE_DEFENSE_INFANTRY_FOOD) {
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_STOCK && b.Project == 0 && b.Percent == 100) {
                BuildingAction(b.SN, BUILDING_STOCK_UPGRADE_DEFENSE_INFANTRY);
                DebugText("仓库升级步兵护甲");
                return;
            }
        }
    }

    // 3. 弓兵护甲升级（当弓手>=4时）
    if (!upgradeStatus.archerArmorUpgraded && landArmy.currentArcher >= 4 &&
        info.Meat >= BUILDING_STOCK_UPGRADE_DEFENSE_ARCHER_FOOD) {
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_STOCK && b.Project == 0 && b.Percent == 100) {
                BuildingAction(b.SN, BUILDING_STOCK_UPGRADE_DEFENSE_ARCHER);
                DebugText("仓库升级弓兵护甲");
                return;
            }
        }
    }

    // 4. 采石技术升级（提升投石兵效果）
    if (landArmy.currentSlinger >= 3 &&
        info.Meat >= BUILDING_MARKET_STONE_UPGRADE_FOOD &&
        info.Stone >= BUILDING_MARKET_STONE_UPGRADE_STONE) {
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_MARKET && b.Project == 0 && b.Percent == 100) {
                BuildingAction(b.SN, BUILDING_MARKET_STONE_UPGRADE);
                DebugText("市场升级采石技术（增强投石兵）");
                return;
            }
        }
    }
}

// 改进的海战指挥（编组作战）
void UsrAI::improvedNavalWarfare() {
    vector<int> availableShips;
    vector<int> enemyShips;

    // 收集可用战船
    for (const tagArmy& ship : info.armies) {
        if (ship.Sort == AT_SHIP && ship.NowState == HUMAN_STATE_IDLE) {
            availableShips.push_back(ship.SN);
        }
    }

    // 收集敌方战船
    for (const tagArmy& enemy : info.enemy_armies) {
        if (enemy.Sort == AT_SHIP) {
            enemyShips.push_back(enemy.SN);
        }
    }

    // 集群攻击：多艘战船攻击同一目标
    if (!availableShips.empty() && !enemyShips.empty()) {
        int targetEnemySN = enemyShips[0];  // 选择第一个敌舰作为目标

        // 派遣最多3艘战船攻击同一目标
        int attackerCount = 0;
        for (int shipSN : availableShips) {
            if (attackerCount >= 3) break;

            HumanAction(shipSN, targetEnemySN);
            DebugText("战船" + to_string(shipSN) + "编队攻击敌舰" + to_string(targetEnemySN));
            attackerCount++;
        }
    }
}

// 检查阶段2完成条件
bool UsrAI::checkStage2Completion() {
    // 检查是否掌控制海权（没有敌方海军）
    bool hasEnemyNavy = false;
    for (const tagArmy& enemy : info.enemy_armies) {
        if (enemy.Sort == AT_SHIP) {
            hasEnemyNavy = true;
            break;
        }
    }

    // 检查是否有足够的陆军
    bool hasAdequateArmy = (landArmy.currentClubman >= 6 &&
                           landArmy.currentSlinger >= 4 &&
                           landArmy.currentArcher >= 4);

    // 检查是否发现敌方大陆
    bool foundEnemyLand = exploration.enemy_mainland_found;

    if (!hasEnemyNavy && hasAdequateArmy && foundEnemyLand) {
        DebugText("======= Stage2完成条件达成！准备进入Stage3 =======");
        return true;
    }

    return false;
}
// Stage2新增：检查升级条件
bool checkUpgradeConditions() {
    int required_buildings = 0;
    bool has_dock = false, has_storage = false, has_barracks = false, has_granary = false;

    for (const tagBuilding& b : info.buildings) {
        switch(b.Type) {
            case BUILDING_DOCK:
                if (b.Percent == 100) { has_dock = true; required_buildings++; }
                break;
            case BUILDING_STOCK:
                if (b.Percent == 100) { has_storage = true; required_buildings++; }
                break;
            case BUILDING_ARMYCAMP:
                if (b.Percent == 100) { has_barracks = true; required_buildings++; }
                break;
            case BUILDING_GRANARY:
                if (b.Percent == 100) { has_granary = true; required_buildings++; }
                break;
        }
    }

    // 新条件：村民数量达到24且粮食达到500且至少2个必要建筑
    int currentPop = info.farmers.size();
    return (required_buildings >= 2 && currentPop >= 24 && info.Meat >= 500);
}
// 检查是否应该停止生产村民以积累食物
bool shouldStopVillagerProduction() {
    // 如果正在升级，停止生产村民
    if (upgrading_in_progress) return true;

    return (info.Meat >= stage1PopControl.food_reserve_threshold) ||
           (info.Meat >= 300 && checkUpgradeConditions());
}
// Stage2新增：升级到工具时代
bool  UsrAI::upgradeToToolAge() {
    for (const tagBuilding& b : info.buildings) {
        if (b.Type == BUILDING_CENTER && b.Project == 0) {
            BuildingAction(b.SN, BUILDING_CENTER_UPGRADE);
            DebugText("开始升级到工具时代！");
            return true;
        }
    }
    return false;
}

// Stage2新增：科技研究优先级
void  UsrAI::researchTechnology() {
    // 1. 市场木材升级（增加射程）
    for (const tagBuilding& b : info.buildings) {
        if (b.Type == BUILDING_MARKET && b.Project == 0 &&
            info.Meat >= BUILDING_MARKET_WOOD_UPGRADE_FOOD &&
            info.Wood >= BUILDING_MARKET_WOOD_UPGRADE_WOOD) {
            BuildingAction(b.SN, BUILDING_MARKET_WOOD_UPGRADE);
            DebugText("研究木材升级技术");
            return;
        }
    }

    // 2. 仓库攻防升级
    for (const tagBuilding& b : info.buildings) {
        if (b.Type == BUILDING_STOCK && b.Project == 0) {
            if (info.Meat >= BUILDING_STOCK_UPGRADE_USETOOL_FOOD) {
                BuildingAction(b.SN, BUILDING_STOCK_UPGRADE_USETOOL);
                DebugText("研究工具使用技术");
                return;
            }
        }
    }
}

// 改进的战船探索（替换原有的exploreOcean函数）
void UsrAI::enhancedWarshipExploration() {
    // 如果还没有生成探索目标，先生成
    if (oceanExplorer.explorationTargets.empty()) {
        oceanExplorer.generateExplorationTargets();
    }

    for (const tagArmy& ship : info.armies) {
        if (ship.Sort == AT_SHIP && ship.NowState == HUMAN_STATE_IDLE) {
            if (!exploration.enemy_mainland_found) {
                // 优先探索远离己方大陆的区域
                auto target = oceanExplorer.getNearestUnexploredTarget(ship.BlockDR, ship.BlockUR);

                if (target.first != -1) {
                    // 优先选择距离己方大陆较远的目标
                    int distFromCenter = getDistance(target.first, target.second, center_x, center_y);
                    if (distFromCenter > 25) {  // 只探索距离中心25格以外的区域
                        double target_x = target.first * BLOCKSIDELENGTH;
                        double target_y = target.second * BLOCKSIDELENGTH;
                        HumanMove(ship.SN, target_x, target_y);
                        DebugText("战船" + to_string(ship.SN) + "远程探索(" +
                                 to_string(target.first) + "," + to_string(target.second) + ")距离中心" +
                                 to_string(distFromCenter) + "格");
                    }
                } else {
                    // 所有预设目标探索完毕，向地图对角探索
                    int target_x = 128 - center_x;
                    int target_y = 128 - center_y;

                    // 确保在有效范围内
                    target_x = max(10, min(118, target_x));
                    target_y = max(10, min(118, target_y));

                    HumanMove(ship.SN, target_x * BLOCKSIDELENGTH, target_y * BLOCKSIDELENGTH);
                    DebugText("战船" + to_string(ship.SN) + "向对角区域深度探索");
                }

                // 标记当前位置为已探索
                oceanExplorer.markAsExplored(ship.BlockDR, ship.BlockUR);
            } else {
                // 已发现敌方大陆，在敌方大陆附近巡逻（扩大范围）
                if (!exploration.enemy_land_positions.empty()) {
                    auto& pos = exploration.enemy_land_positions[0];
                    // 扩大巡逻范围到±30格
                    int patrol_x = pos.first + (rand() % 61 - 30);  // ±30范围巡逻
                    int patrol_y = pos.second + (rand() % 61 - 30);
                    patrol_x = max(5, min(123, patrol_x));
                    patrol_y = max(5, min(123, patrol_y));

                    HumanMove(ship.SN, patrol_x * BLOCKSIDELENGTH, patrol_y * BLOCKSIDELENGTH);
                    DebugText("战船" + to_string(ship.SN) + "在敌方海域大范围巡逻");
                }
            }
        }
    }
}

// 新增：统计探索进度
void UsrAI::reportExplorationProgress() {
    if (info.GameFrame % 300 == 0) {  // 每300帧（约15秒）报告一次
        int totalTargets = oceanExplorer.explorationTargets.size();
        int exploredCount = 0;

        for (auto& target : oceanExplorer.explorationTargets) {
            for (auto& explored : oceanExplorer.exploredOceanTiles) {
                if (getDistance(target.first, target.second, explored.first, explored.second) < 20) {
                    exploredCount++;
                    break;
                }
            }
        }

        double progress = (double)exploredCount / totalTargets * 100;
        DebugText("海洋探索进度: " + to_string(exploredCount) + "/" + to_string(totalTargets) +
                  " (" + to_string((int)progress) + "%)");
    }
}


// Stage2新增：检测敌方大陆
void  UsrAI::detectEnemyLand() {
    for (int i = 0; i < 128; i++) {
        for (int j = 0; j < 128; j++) {
            if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS) {
                // 检查是否远离己方市镇中心（可能是敌方大陆）
                int dist = getDistance(i, j, center_x, center_y);
                if (dist > 30) {  // 距离阈值
                    exploration.enemy_land_positions.push_back({i, j});
                    if (!exploration.enemy_mainland_found) {
                        exploration.enemy_mainland_found = true;
                        DebugText("发现敌方大陆位置：(" + to_string(i) + "," + to_string(j) + ")");
                    }
                }
            }
        }
    }
}

// Stage2新增：海战逻辑
void  UsrAI::conductNavalWarfare() {
    // 检测敌方海军
    for (const tagArmy& enemy : info.enemy_armies) {
        if (enemy.Sort == AT_SHIP) {  // 敌方战船
            // 派遣最近的己方战船攻击
            int nearest_ship = -1;
            double min_dist = 1e9;

            for (const tagArmy& ship : info.armies) {
                if (ship.Sort == AT_SHIP && ship.NowState == HUMAN_STATE_IDLE) {
                    double dist = getExactDistanceSquared(ship.DR, ship.UR, enemy.DR, enemy.UR);
                    if (dist < min_dist) {
                        min_dist = dist;
                        nearest_ship = ship.SN;
                    }
                }
            }

            if (nearest_ship != -1) {
                HumanAction(nearest_ship, enemy.SN);
                DebugText("战船" + to_string(nearest_ship) + "攻击敌方战船" + to_string(enemy.SN));
            }
            break;  // 一次处理一个敌人
        }
    }
}

// 原有函数保持不变
void UsrAI::updateMap() {
    memset(game_map, 0, 128 * 128 * sizeof(char));

    for (int i = 0; i < 128; i++) {
        for (int j = 0; j < 128; j++) {
            if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS) {
                game_map[i][j] = 1;
            } else if ((*info.theMap)[i][j].type == MAPPATTERN_OCEAN) {
                game_map[i][j] = 2;
            }
        }
    }

    for (const tagBuilding& b : info.buildings) {
        int size = (b.Type == BUILDING_CENTER) ? 3 :
                  (b.Type == BUILDING_HOME || b.Type == BUILDING_DOCK) ? 2 : 3;
        for (int i = b.BlockDR; i < b.BlockDR + size && i < 128; i++) {
            for (int j = b.BlockUR; j < b.BlockUR + size && j < 128; j++) {
                game_map[i][j] = 3;
            }
        }
        // 修改：只有完全建成的船坞才设置为dock_built
           if (b.Type == BUILDING_DOCK && b.Percent == 100) {  // 添加完成度检查
               dock_built = true;
               dock_sn = b.SN;
        }
    }

    for (const tagBuilding& b : info.enemy_buildings) {
        int size = (b.Type == BUILDING_CENTER) ? 3 :
                  (b.Type == BUILDING_HOME) ? 2 : 3;
        for (int i = b.BlockDR; i < b.BlockDR + size && i < 128; i++) {
            for (int j = b.BlockUR; j < b.BlockUR + size && j < 128; j++) {
                game_map[i][j] = 4;
            }
        }
    }

    for (const tagResource& res : info.resources) {
        if (res.BlockDR >= 0 && res.BlockDR < 128 && res.BlockUR >= 0 && res.BlockUR < 128) {
            game_map[res.BlockDR][res.BlockUR] = 5;
        }
    }
}


bool findDockPosition(int& dock_x, int& dock_y) {
    int bestX = -1, bestY = -1;
    int minDist = 9999;

    // 先搜索紧邻陆地的海洋位置
    for (int radius = 3; radius <= 25; radius++) {
        for (int angle = 0; angle < 360; angle += 15) {  // 更密集的角度搜索
            int i = center_x + radius * cos(angle * 3.14159 / 180);
            int j = center_y + radius * sin(angle * 3.14159 / 180);

            // 确保在地图范围内
            if (i < 2 || i + 1 >= 126 || j < 2 || j + 1 >= 126) continue;

            // 检查2x2区域是否都是海洋
            if (game_map[i][j] != 2 || game_map[i+1][j] != 2 ||
                game_map[i][j+1] != 2 || game_map[i+1][j+1] != 2) continue;

            // 关键改进：检查是否至少有一边直接相邻陆地
            bool hasAdjacentLand = false;
            // 检查四个边是否有陆地相邻
            for (int di = 0; di <= 1; di++) {
                for (int dj = 0; dj <= 1; dj++) {
                    // 检查上下左右四个方向
                    if ((i + di - 1 >= 0 && game_map[i + di - 1][j + dj] == 1) ||  // 左
                        (i + di + 1 < 128 && game_map[i + di + 1][j + dj] == 1) ||  // 右
                        (j + dj - 1 >= 0 && game_map[i + di][j + dj - 1] == 1) ||  // 上
                        (j + dj + 1 < 128 && game_map[i + di][j + dj + 1] == 1)) {  // 下
                        hasAdjacentLand = true;
                        break;
                    }
                }
                if (hasAdjacentLand) break;
            }

            if (!hasAdjacentLand) continue;

            // 确保周围没有其他建筑冲突
            bool isFree = true;
            for (int di = -1; di <= 2; di++) {
                for (int dj = -1; dj <= 2; dj++) {
                    int ni = i + di, nj = j + dj;
                    if (ni >= 0 && ni < 128 && nj >= 0 && nj < 128) {
                        if (game_map[ni][nj] >= 3) {  // 有建筑或资源
                            isFree = false;
                            break;
                        }
                    }
                }
                if (!isFree) break;
            }

            if (isFree) {
                int dist = getDistance(i, j, center_x, center_y);
                if (dist < minDist) {
                    minDist = dist;
                    bestX = i;
                    bestY = j;
                }
            }
        }
        if (bestX != -1) break;  // 找到合适位置就停止
    }

    if (bestX != -1) {
        dock_x = bestX;
        dock_y = bestY;
        return true;
    }
    return false;
}
// 检查村民是否能到达船坞建造位置附近的陆地
bool canReachDockPosition(int farmer_x, int farmer_y, int dock_x, int dock_y) {
    // 检查船坞周围是否有陆地供村民站立
    for (int di = -1; di <= 2; di++) {
        for (int dj = -1; dj <= 2; dj++) {
            int land_x = dock_x + di;
            int land_y = dock_y + dj;

            if (land_x >= 0 && land_x < 128 && land_y >= 0 && land_y < 128) {
                if (game_map[land_x][land_y] == 1) {  // 是陆地
                    // 简单距离检查，确保村民能够合理到达
                    int dist = getDistance(farmer_x, farmer_y, land_x, land_y);
                    if (dist < 50) {  // 距离阈值
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
bool findStoragePosition(int& storage_x, int& storage_y) {
    int gazelleX = -1, gazelleY = -1;
    for (const tagResource& res : info.resources) {
        if (res.Type == RESOURCE_GAZELLE) {
            gazelleX = res.BlockDR;
            gazelleY = res.BlockUR;
            break;
        }
    }

    if (gazelleX == -1) return false;

    for (int radius = 2; radius <= 6; radius++) {
        for (int i = gazelleX - radius; i <= gazelleX + radius; i++) {
            for (int j = gazelleY - radius; j <= gazelleY + radius; j++) {
                if (i >= 0 && i + 2 < 128 && j >= 0 && j + 2 < 128) {
                    bool canBuild = true;
                    for (int di = 0; di < 3; di++) {
                        for (int dj = 0; dj < 3; dj++) {
                            if (game_map[i+di][j+dj] != 1) {
                                canBuild = false;
                                break;
                            }
                        }
                        if (!canBuild) break;
                    }

                    if (canBuild && isAreaFree(i, j, 3)) {
                        storage_x = i;
                        storage_y = j;
                        return true;
                    }
                }
            }
        }
    }
    return false;
}


bool isResourceValid(int resSN) {
    for (const tagResource& res : info.resources) {
        if (res.SN == resSN && res.Cnt > 0) {
            return true;
        }
    }
    return false;
}

bool lockResource(int resSN) {
    if (resourceLocks.find(resSN) == resourceLocks.end()) {
        resourceLocks[resSN] = false;
    }
    if (!resourceLocks[resSN] && isResourceValid(resSN)) {
        resourceLocks[resSN] = true;
        return true;
    }
    return false;
}

void unlockResource(int resSN) {
    if (resourceLocks.find(resSN) != resourceLocks.end()) {
        resourceLocks[resSN] = false;
    }
}

int findNearestResource(int x, int y, int resourceType) {
    int nearest_sn = -1;
    double min_dist = 1e9;

    for (const tagResource& res : info.resources) {
        if (res.Type == resourceType && res.Cnt > 0 && lockResource(res.SN)) {
            double dist = getExactDistanceSquared(x, y, res.DR, res.UR);
            if (dist < min_dist) {
                if (nearest_sn != -1) unlockResource(nearest_sn);
                min_dist = dist;
                nearest_sn = res.SN;
            } else {
                unlockResource(res.SN);
            }
        }
    }
    return nearest_sn;
}

void updateWorkForceCount() {
    resourceTargets.current_woodcutters = 0;
    resourceTargets.current_hunters = 0;
    resourceTargets.current_miners = 0;
    resourceTargets.current_fishers = 0;

    for (const tagFarmer& farmer : info.farmers) {
        if (farmer.FarmerSort == 0 && farmer.NowState == HUMAN_STATE_WORKING) {
            for (const tagResource& res : info.resources) {
                if (res.SN == farmer.WorkObjectSN) {
                    switch (res.Type) {
                        case RESOURCE_TREE:
                            resourceTargets.current_woodcutters++;
                            break;
                        case RESOURCE_GAZELLE:
                        case RESOURCE_ELEPHANT:
                            resourceTargets.current_hunters++;
                            break;
                        case RESOURCE_STONE:
                            resourceTargets.current_miners++;
                            break;
                    }
                    break;
                }
            }
        } else if (farmer.FarmerSort == 2) {
            resourceTargets.current_fishers++;
        }
    }

    // Stage2新增：统计战船数量
    naval.current_warships = 0;
    naval.warship_sns.clear();
    for (const tagArmy& army : info.armies) {
        if (army.Sort == AT_SHIP) {
            naval.current_warships++;
            naval.warship_sns.push_back(army.SN);
        }
    }
}

// 改进的船坞位置搜索（如果标准方法失败）
bool findNearestShorePosition(int& dock_x, int& dock_y) {
    int bestX = -1, bestY = -1;
    int minDist = 9999;

    // 从市镇中心开始，螺旋搜索最近的海岸线
    for (int radius = 5; radius <= 30; radius++) {
        for (int i = max(2, center_x - radius); i <= min(125, center_x + radius); i++) {
            for (int j = max(2, center_y - radius); j <= min(125, center_y + radius); j++) {
                // 必须是海洋位置
                if (game_map[i][j] != 2 || game_map[i+1][j] != 2 ||
                    game_map[i][j+1] != 2 || game_map[i+1][j+1] != 2) continue;

                // 必须紧邻陆地（至少一边相邻）
                bool isShore = false;
                if ((i > 0 && (game_map[i-1][j] == 1 || game_map[i-1][j+1] == 1)) ||
                    (i+1 < 127 && (game_map[i+2][j] == 1 || game_map[i+2][j+1] == 1)) ||
                    (j > 0 && (game_map[i][j-1] == 1 || game_map[i+1][j-1] == 1)) ||
                    (j+1 < 127 && (game_map[i][j+2] == 1 || game_map[i+1][j+2] == 1))) {
                    isShore = true;
                }

                if (isShore && isAreaFree(i, j, 2)) {
                    int dist = getDistance(i, j, center_x, center_y);
                    if (dist < minDist) {
                        minDist = dist;
                        bestX = i;
                        bestY = j;
                    }
                }
            }
        }
        if (bestX != -1) break;
    }

    if (bestX != -1) {
        dock_x = bestX;
        dock_y = bestY;
        return true;
    }
    return false;
}
// 查找距离市镇中心指定范围的建筑位置
bool findDistantBuildingPosition(int& build_x, int& build_y, int min_dist, int max_dist) {
    for (int radius = min_dist; radius <= max_dist; radius++) {
        // 使用螺旋搜索避免多个村民选择同一位置
        for (int angle = 0; angle < 360; angle += 45) {
            int i = center_x + radius * cos(angle * 3.14159 / 180);
            int j = center_y + radius * sin(angle * 3.14159 / 180);

            // 确保在地图范围内
            if (i < 0 || i + 2 >= 128 || j < 0 || j + 2 >= 128) continue;

            // 检查距离是否合适
            int dist = getDistance(i, j, center_x, center_y);
            if (dist < min_dist || dist > max_dist) continue;

            // 检查3x3区域是否为草地且平坦
            bool canBuild = true;
            int height = -1;

            // 扩大检查范围到4x4，确保周围没有冲突
            for (int di = -1; di < 4; di++) {
                for (int dj = -1; dj < 4; dj++) {
                    int check_i = i + di, check_j = j + dj;
                    if (check_i < 0 || check_i >= 128 || check_j < 0 || check_j >= 128) {
                        canBuild = false;
                        break;
                    }

                    // 检查是否有其他建筑或资源
                    if (game_map[check_i][check_j] >= 3) {  // 3=己方建筑, 4=敌方建筑, 5=资源
                        canBuild = false;
                        break;
                    }

                    // 核心3x3区域必须是草地
                    if (di >= 0 && di < 3 && dj >= 0 && dj < 3) {
                        if (game_map[check_i][check_j] != 1) {  // 不是草地
                            canBuild = false;
                            break;
                        }

                        // 检查高度一致性
                        if (height == -1) {
                            height = (*info.theMap)[check_i][check_j].height;
                        } else if ((*info.theMap)[check_i][check_j].height != height) {
                            canBuild = false;
                            break;
                        }
                    }
                }
                if (!canBuild) break;
            }

            if (canBuild) {
                build_x = i;
                build_y = j;
                return true;
            }
        }
    }
    return false;
}
void UsrAI::assignOptimalTask(tagFarmer& farmer) {
    // 升级期间所有村民都去伐木
       if (upgrading_in_progress) {
           int treeSN = findNearestResource(farmer.BlockDR, farmer.BlockUR, RESOURCE_TREE);
           if (treeSN != -1) {
               HumanAction(farmer.SN, treeSN);
               DebugText("升级期间村民" + to_string(farmer.SN) + "专心伐木");
               return;
           }
       }

       // Stage1必要建筑建设（在原有dock建设前添加）
       if (stage == 1) {
           // 检查并建造必要建筑
           bool hasBarracks = false, hasGranary = false, hasStorage = false;
           for (const tagBuilding& b : info.buildings) {
               if (b.Type == BUILDING_ARMYCAMP && b.Percent == 100) hasBarracks = true;
               if (b.Type == BUILDING_GRANARY && b.Percent == 100) hasGranary = true;
               if (b.Type == BUILDING_STOCK && b.Percent == 100) hasStorage = true;
           }

           // 建造兵营（距离市镇中心较远）
           if (!hasBarracks && info.Wood >= BUILD_ARMYCAMP_WOOD) {
               int barracks_x, barracks_y;
               if (findDistantBuildingPosition(barracks_x, barracks_y, 8, 15)) {  // 距离8-15格
                   HumanBuild(farmer.SN, BUILDING_ARMYCAMP, barracks_x, barracks_y);
                   DebugText("村民" + to_string(farmer.SN) + "建造兵营");
                   return;
               }
           }

           // 建造谷仓
           if (!hasGranary && info.Wood >= BUILD_GRANARY_WOOD) {
               int granary_x, granary_y;
               if (findDistantBuildingPosition(granary_x, granary_y, 6, 12)) {
                   HumanBuild(farmer.SN, BUILDING_GRANARY, granary_x, granary_y);
                   DebugText("村民" + to_string(farmer.SN) + "建造谷仓");
                   return;
               }
           }

           // 建造仓库（如果还没有）
           if (!hasStorage && info.Wood >= BUILD_STOCK_WOOD) {
               int storage_x, storage_y;
               if (findDistantBuildingPosition(storage_x, storage_y, 6, 12)) {
                   HumanBuild(farmer.SN, BUILDING_STOCK, storage_x, storage_y);
                   DebugText("村民" + to_string(farmer.SN) + "建造仓库");
                   return;
               }
           }
       }

       // 改进的船坞建造逻辑：使用备用策略
       if (!dock_built && !buildingTracker.dock_building && dock_build_attempts == 0 && info.Wood >= BUILD_DOCK_WOOD) {
           dock_build_attempts++;
           int dock_x, dock_y;

           // 首先尝试标准方法
           bool positionFound = findDockPosition(dock_x, dock_y);

           // 如果标准方法失败，尝试备用方法
           if (!positionFound) {
               positionFound = findNearestShorePosition(dock_x, dock_y);
               if (positionFound) {
                   DebugText("使用备用策略寻找船坞位置");
               }
           }

           if (positionFound && canReachDockPosition(farmer.BlockDR, farmer.BlockUR, dock_x, dock_y)) {
               HumanBuild(farmer.SN, BUILDING_DOCK, dock_x, dock_y);
               DebugText("村民" + to_string(farmer.SN) + "建造船坞在海岸位置(" + to_string(dock_x) + "," + to_string(dock_y) + ")");
               return;
           } else {
               DebugText("村民" + to_string(farmer.SN) + "船坞建造失败");
           }
       }
    // Stage2优先级调整：如果在Stage2，优先保证木材供应
    if (stage == 2) {
        // 优先建造市场（如果还没有）
        bool hasMarket = false;
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_MARKET) {
                hasMarket = true;
                break;
            }
        }

        if (!hasMarket && info.Wood >= BUILD_MARKET_WOOD) {
            int market_x, market_y;
            if (find_block(market_x, market_y)) {
                HumanBuild(farmer.SN, BUILDING_MARKET, market_x, market_y);
                DebugText("村民" + to_string(farmer.SN) + "建造市场");
                return;
            }
        }
    }

    int currentPop = info.farmers.size() + info.armies.size();
    int popSpace = info.Human_MaxNum - currentPop;
    if (popSpace < 5 && info.Wood >= BUILD_HOUSE_WOOD) {
        int home_x, home_y;
        if (find_block(home_x, home_y) && isAreaFree(home_x, home_y)) {
            HumanBuild(farmer.SN, BUILDING_HOME, home_x, home_y);
            DebugText("村民" + to_string(farmer.SN) + "建造房屋（缓解人口瓶颈）");
            return;
        }
    }
    // Stage1：有多余木头时建造必要建筑（新增逻辑）
        if (stage == 1 && info.Wood >= 200) {  // 有足够多余木头时
            // 更新建造状态
            buildingTracker.updateStatus();

            // 检查已有建筑
            bool hasBarracks = false, hasGranary = false, hasStorage = false;
            for (const tagBuilding& b : info.buildings) {
                if (b.Type == BUILDING_ARMYCAMP) hasBarracks = true;
                if (b.Type == BUILDING_GRANARY) hasGranary = true;
                if (b.Type == BUILDING_STOCK) hasStorage = true;
            }

            // 优先顺序：仓库 → 谷仓 → 兵营
            if (!hasStorage && !buildingTracker.storage_building && info.Wood >= BUILD_STOCK_WOOD) {
                int storage_x, storage_y;
                if (findDistantBuildingPosition(storage_x, storage_y, 6, 12)) {
                    HumanBuild(farmer.SN, BUILDING_STOCK, storage_x, storage_y);
                    DebugText("村民" + to_string(farmer.SN) + "建造仓库（多余木头）");
                    return;
                }
            }

            if (!hasGranary && !buildingTracker.granary_building && info.Wood >= BUILD_GRANARY_WOOD) {
                int granary_x, granary_y;
                if (findDistantBuildingPosition(granary_x, granary_y, 6, 12)) {
                    HumanBuild(farmer.SN, BUILDING_GRANARY, granary_x, granary_y);
                    DebugText("村民" + to_string(farmer.SN) + "建造谷仓（多余木头）");
                    return;
                }
            }

            if (!hasBarracks && !buildingTracker.barracks_building && info.Wood >= BUILD_ARMYCAMP_WOOD) {
                int barracks_x, barracks_y;
                if (findDistantBuildingPosition(barracks_x, barracks_y, 8, 15)) {
                    HumanBuild(farmer.SN, BUILDING_ARMYCAMP, barracks_x, barracks_y);
                    DebugText("村民" + to_string(farmer.SN) + "建造兵营（多余木头）");
                    return;
                }
            }
        }
    bool hasGazelleStore = false;
    for (const tagBuilding& b : info.buildings) {
        if (b.Type == BUILDING_STOCK) {
            hasGazelleStore = true;
            break;
        }
    }

    if (!hasGazelleStore && info.Wood >= BUILD_STOCK_WOOD) {
        int storage_x, storage_y;
        if (findStoragePosition(storage_x, storage_y)) {
            HumanBuild(farmer.SN, BUILDING_STOCK, storage_x, storage_y);
            DebugText("村民" + to_string(farmer.SN) + "建造羚羊仓库");
            return;
        }
    }

    // 按照资源缺口优先级分配工作
    int neededJobType = resourceTargets.getMostNeededJob();

    if (resourceTargets.needMoreWorkers(neededJobType)) {
        int resourceSN = findNearestResource(farmer.BlockDR, farmer.BlockUR, neededJobType);
        if (resourceSN != -1) {
            HumanAction(farmer.SN, resourceSN);
            string jobName = (neededJobType == RESOURCE_TREE) ? "砍树" :
                           (neededJobType == RESOURCE_GAZELLE) ? "打猎" : "采石";
            DebugText("优先分配村民" + to_string(farmer.SN) + jobName);
            return;
        }
    }

    vector<int> jobPriority = {RESOURCE_TREE, RESOURCE_GAZELLE, RESOURCE_STONE};

    for (int jobType : jobPriority) {
        if (resourceTargets.needMoreWorkers(jobType)) {
            int resourceSN = findNearestResource(farmer.BlockDR, farmer.BlockUR, jobType);
            if (resourceSN != -1) {
                HumanAction(farmer.SN, resourceSN);
                string jobName = (jobType == RESOURCE_TREE) ? "砍树" :
                               (jobType == RESOURCE_GAZELLE) ? "打猎" : "采石";
                DebugText("补充分配村民" + to_string(farmer.SN) + jobName);
                return;
            }
        }
    }

    int treeSN = findNearestResource(farmer.BlockDR, farmer.BlockUR, RESOURCE_TREE);
    if (treeSN != -1) {
        HumanAction(farmer.SN, treeSN);
        DebugText("额外分配村民" + to_string(farmer.SN) + "砍树");
        return;
    }

    HumanMove(farmer.SN, farmer.DR + 35.7, farmer.UR + 35.7);
    DebugText("村民" + to_string(farmer.SN) + "探索");
}
// 在processData中的Stage2部分添加这些调用
void UsrAI::enhancedStage2Logic() {
    // 更新军事状态
    landArmy.updateCounts();
    militaryBuildings.updateStatus();
    upgradeStatus.checkUpgrades();

    // 人口优化
    optimizePopulation();

    // 军事建设
    buildMilitaryInfrastructure();

    // 陆军生产
    produceLandArmy();

    // 军事升级
    manageMilitaryUpgrades();

    // 改进的海战
    improvedNavalWarfare();

    // 检查阶段完成
    if (checkStage2Completion()) {
        // 可以在这里设置stage = 3的条件
        DebugText("Stage2目标已达成，准备登陆作战！");
    }

    // 调试信息
    DebugText("陆军状态 - 棍棒兵:" + to_string(landArmy.currentClubman) + "/" + to_string(landArmy.clubmanTarget) +
              " 投石兵:" + to_string(landArmy.currentSlinger) + "/" + to_string(landArmy.slingerTarget) +
              " 弓箭手:" + to_string(landArmy.currentArcher) + "/" + to_string(landArmy.archerTarget) +
              " 骑兵:" + to_string(landArmy.currentScout) + "/" + to_string(landArmy.scoutTarget));
}
// 主处理逻辑（增强Stage1->Stage2升级和Stage2功能）
void UsrAI::processData() {
    info = getInfo();
    updateMap();
    updateWorkForceCount();
    resourceLocks.clear();
    // 重置建造计数器
        dock_build_attempts = 0;
    // 更新建造跟踪状态
        buildingTracker.updateStatus();
    // 检测游戏阶段变化
    if (stage == 1 && info.civilizationStage == CIVILIZATION_TOOLAGE) {
        stage = 2;
        resourceTargets.adjustForStage2();  // 调整资源分配目标
        DebugText("======= 进入Stage2：工具时代 =======");
    }

    if (center_x == 0 && center_y == 0) {
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_CENTER) {
                center_x = b.BlockDR;
                center_y = b.BlockUR;
                begin_x = max(0, center_x - 5);
                begin_y = max(0, center_y - 5);
                break;
            }
        }
    }

    home_count = 0;
    fishing_boat_count = 0;
    for (const tagBuilding& building : info.buildings) {
        if (building.Type == BUILDING_HOME) {
            home_count++;
        }
    }

    for (const tagFarmer& farmer : info.farmers) {
        if (farmer.FarmerSort == 2) {
            fishing_boat_count++;
        }
    }

    home_flag = (home_count > 0);
    if (stage == 1) {
        // 检查是否正在升级（通过市镇中心的项目状态判断）
        upgrading_in_progress = false;  // 先重置状态
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_CENTER && b.Project == BUILDING_CENTER_UPGRADE) {
                upgrading_in_progress = true;
                DebugText("升级进行中，所有村民专心伐木（进度:" + to_string(b.ProjectPercent) + "%）");
                break;
            }
        }

        // 如果没有在升级且满足升级条件，开始升级
        if (!upgrading_in_progress && checkUpgradeConditions()) {
            if (upgradeToToolAge()) {
                upgrading_in_progress = true;
                DebugText("满足升级条件（人口:" + to_string(info.farmers.size()) + "/24，食物:" + to_string(info.Meat) + "/500），开始升级！");
                return;  // 升级中，本帧不执行其他操作
            }
        }

        // 如果正在升级，显示状态信息但不执行其他逻辑
        if (upgrading_in_progress) {
            return;
        }
    }
    // Stage2专属逻辑
    if (stage == 2) {
        // 1. 研究科技
        researchTechnology();

        // 2. 建造必要建筑（谷仓用于解锁箭塔）
        bool hasGranary = false;
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_GRANARY) {
                hasGranary = true;
                break;
            }
        }

        if (!hasGranary && info.Wood >= BUILD_GRANARY_WOOD) {
            for (auto& farmer : info.farmers) {
                if (farmer.FarmerSort == 0 && farmer.NowState == HUMAN_STATE_IDLE) {
                    int granary_x, granary_y;
                    if (find_block(granary_x, granary_y)) {
                        HumanBuild(farmer.SN, BUILDING_GRANARY, granary_x, granary_y);
                        DebugText("建造谷仓");
                        break;
                    }
                }
            }
        }

        // 3. 大量生产战船（优先级提升）
        if (naval.current_warships < naval.target_warships && info.Wood >= BUILDING_DOCK_CREATE_SHIP_WOOD) {
            for (const auto& b : info.buildings) {
                if (b.Type == BUILDING_DOCK && b.Project == 0) {
                    BuildingAction(b.SN, BUILDING_DOCK_CREATE_SHIP);
                    DebugText("船坞生产战船（" + to_string(naval.current_warships) + "/" +
                             to_string(naval.target_warships) + "）");
                    break;
                }
            }
        }

        // 4. 海洋探索和海战
        detectEnemyLand();
        conductNavalWarfare();
        enhancedWarshipExploration();
        // 5. 新增：完整的Stage2军事建设
        enhancedStage2Logic();
        // 5. 新增：运输船探索和进度报告
        exploreWithTransportShips();
        reportExplorationProgress();

    }
    // 村民生产逻辑（Stage1优化）
    int currentPop = info.farmers.size() + info.armies.size();
    bool shouldProduceVillager = false;

    if (stage == 1) {
        // Stage1：限制人口并为升级积累食物
        stage1PopControl.saving_for_upgrade = shouldStopVillagerProduction();

        if (!stage1PopControl.saving_for_upgrade &&
            currentPop < stage1PopControl.max_population_stage1 &&
            info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD) {
            shouldProduceVillager = true;
        }

        if (stage1PopControl.saving_for_upgrade) {
            DebugText("Stage1：停止生产村民，积累食物准备升级（食物:" + to_string(info.Meat) + "/500）");
        }
    } else {
        // Stage2：正常人口控制
        int targetPop = info.Human_MaxNum - 10;  // 预留军事单位空间
        if (currentPop < targetPop && info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD) {
            shouldProduceVillager = true;
        }
    }

    if (shouldProduceVillager) {
        for (const auto& b : info.buildings) {
            if (b.Type == BUILDING_CENTER && b.Project == 0) {
                BuildingAction(b.SN, BUILDING_CENTER_CREATEFARMER);
                string popInfo = (stage == 1) ?
                    to_string(currentPop) + "/" + to_string(stage1PopControl.max_population_stage1) :
                    to_string(currentPop) + "/" + to_string(info.Human_MaxNum);
                DebugText("生产村民（当前" + popInfo + "）");
                break;
            }
        }
    }
    // 通用逻辑：渔船生产和管理
    if (dock_built && fishing_boat_count < resourceTargets.target_fishers && info.Wood >= 60) {
        for (const auto& b : info.buildings) {
            if (b.Type == BUILDING_DOCK && b.Project == 0 && (stage == 1 || naval.current_warships >= naval.target_warships)) {
                BuildingAction(b.SN, BUILDING_DOCK_CREATE_SAILING);
                DebugText("船坞造渔船（" + to_string(fishing_boat_count) + "/" +
                         to_string(resourceTargets.target_fishers) + "）");
                break;
            }
        }
    }

   enhancedFishingExploration();

    // 通用逻辑：陆地村民任务分配
    for (auto& farmer : info.farmers) {
        if (farmer.FarmerSort == 0 && farmer.NowState == HUMAN_STATE_IDLE) {
            assignOptimalTask(farmer);
        }
    }
    // 新增：运输船探索和进度报告
    exploreWithTransportShips();
    reportExplorationProgress();
    // 调试信息
    string stageInfo = (stage == 1) ? "Stage1" : "Stage2";
    DebugText(stageInfo + " - 砍树:" + to_string(resourceTargets.current_woodcutters) + "/" + to_string(resourceTargets.target_woodcutters) +
              " 打猎:" + to_string(resourceTargets.current_hunters) + "/" + to_string(resourceTargets.target_hunters) +
              " 采石:" + to_string(resourceTargets.current_miners) + "/" + to_string(resourceTargets.target_miners) +
              " 捕鱼:" + to_string(fishing_boat_count) + "/" + to_string(resourceTargets.target_fishers));
    if (stage == 1) {
        string popStatus = stage1PopControl.saving_for_upgrade ? "积累中" : "正常生产";
        DebugText("Stage1人口控制: " + to_string(currentPop) + "/" +
                  to_string(stage1PopControl.max_population_stage1) +
                  " 状态:" + popStatus + " 食物:" + to_string(info.Meat) + "/500");
    }
    if (stage == 2) {
        DebugText("战船数量: " + to_string(naval.current_warships) + "/" + to_string(naval.target_warships) +
                  " 敌方大陆: " + (exploration.enemy_mainland_found ? "已发现" : "未发现"));
    }
}

